package com.sq.activity.service.impl;

import java.time.LocalDate;
import java.util.List;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.sq.common.core.domain.AjaxResult;
import com.sq.common.core.domain.entity.SysRole;
import com.sq.common.core.domain.entity.SysUser;
import com.sq.common.utils.DateUtils;
import com.sq.common.utils.UserThreadLocal;
import com.sq.system.domain.SysNotice;
import com.sq.system.mapper.SysUserMapper;
import com.sq.system.service.ISysNoticeService;
import com.sq.system.service.ISysUserService;
import org.apache.ibatis.javassist.compiler.ast.Variable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sq.activity.mapper.ActivityMapper;
import com.sq.activity.domain.Activity;
import com.sq.activity.service.IActivityService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;

/**
 * 活动信息Service业务层处理
 * 
 * @author shan
 * @date 2025-02-12
 */
@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements IActivityService {
    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ISysNoticeService sysNoticeService;
    /**
     * 查询活动信息
     * 
     * @param id 活动信息主键
     * @return 活动信息
     */
    @Override
    public Activity selectActivityById(Long id) {
        return activityMapper.selectonId(id);
    }

    /**
     * 查询活动信息列表
     * 
     * @param activity 活动信息
     * @return 活动信息
     */
    @Override
    public List<Activity> selectActivityList(Activity activity)
    {
        return activityMapper.selectActivityList(activity);
    }

    /**
     * 新增活动信息
     * 
     * @param activity 活动信息
     * @return 结果
     */
    @Override
    public AjaxResult insertActivity(Activity activity) {
        //非空判断
        if(ObjectUtils.isEmpty(activity)){
            return AjaxResult.error("活动信息不能为空");
        }
        //判断活动标题是否重复
        if(activityMapper.getOneByTitle(activity.getTitle())!=null){
            return AjaxResult.error("活动标题重复");
        }
        //判断活动开始时间是否小于当前时间
        if(activity.getStartTime().isBefore(LocalDate.now())){
            return AjaxResult.error("活动开始时间不能小于当前时间");
        }
        //判断活动结束时间是否小于活动开始时间
        if(activity.getEndTime().isBefore(activity.getStartTime())){
            return AjaxResult.error("活动结束时间不能小于活动开始时间");
        }
        //判断当前用户是否有权限发布活动
        SysUser sysUser = sysUserMapper.selectUserById(UserThreadLocal.getUserId());
        if (sysUser.getStatus().equals("0")) {
            //获取用户角色
            List<SysRole> roles = sysUser.getRoles();
            for (SysRole role : roles) {
                //判断角色状态是否正常，是否是普通用户
                if(!(role.getStatus().equals("1") && role.getRoleKey().equals("common"))){
                    activity.setSysUserId(UserThreadLocal.getUserId());
                    activity.setSysUserName(sysUser.getUserName());
                    activity.setParticipants(0l);
                    int i = activityMapper.insertActivity(activity);
                    //发布成功，同时发布公告
                    SysNotice sysNotice = new SysNotice();
                    sysNotice.setNoticeTitle("活动发布:" + activity.getTitle());
                    sysNotice.setNoticeType("2");
                    sysNotice.setNoticeContent(activity.getDescription()+activity.getImage());//拼接活动描述和活动图片
                    sysNotice.setStatus("0");
                    sysNoticeService.insertNotice(sysNotice);
                    return i>0?AjaxResult.success():AjaxResult.error();
                }
            }
        }
        return AjaxResult.error("没有发布权限，请申请成为发布者");
    }

    /**
     * 修改活动信息
     * 
     * @param activity 活动信息
     * @return 结果
     */
    @Override
    public AjaxResult updateActivity(Activity activity) {
        //非空判断
        if(ObjectUtils.isEmpty(activity)){
            return AjaxResult.error("活动信息不能为空");
        }
        //判断当前用户是否有权限修改活动
        SysUser sysUser = sysUserMapper.selectUserById(UserThreadLocal.getUserId());
        if (sysUser.getStatus().equals("0")) {
            //获取用户角色
            List<SysRole> roles = sysUser.getRoles();
            for (SysRole role : roles) {
                //判断角色状态是否正常，是否是普通用户
                if(!(role.getStatus().equals("1") && role.getRoleKey().equals("common"))){
                    activity.setSysUserId(UserThreadLocal.getUserId());
                    activity.setSysUserName(sysUser.getUserName());
                    int i = activityMapper.updateActivity(activity);
                    return i>0?AjaxResult.success():AjaxResult.error();
                }
            }
        }
        return AjaxResult.error("没有修改权限，请申请成为发布者");
    }

    /**
     * 批量删除活动信息
     * 
     * @param ids 需要删除的活动信息主键
     * @return 结果
     */
    @Override
    public int deleteActivityByIds(Long[] ids) {
        //判断当前用户是否有权限删除活动
        SysUser sysUser = sysUserMapper.selectUserById(UserThreadLocal.getUserId());
        if (sysUser.getStatus().equals("0")) {
            //获取用户角色
            List<SysRole> roles = sysUser.getRoles();
            for (SysRole role : roles) {
                //判断角色状态是否正常，是否是普通用户
                if(role.getStatus().equals("0") && role.getRoleKey().equals("admin")){
                    //管理员可以删除所有活动
                    return activityMapper.deleteActivityByIds(ids);
                } else if (role.getStatus().equals("0") && role.getRoleKey().equals("activityPublisher")) {
                    Arrays.stream(ids).forEach(id->{
                        //组织者只能删除自己的活动
                        Activity activity = activityMapper.selectActivityById(id);
                        Long sysUserId = activity.getSysUserId();
                        if (sysUserId.equals(UserThreadLocal.getUserId())) {
                            activityMapper.deleteActivityById(id);
                        }
                    });
                }
            }
        }
        return 0;
    }

    /**
     * 删除活动信息信息
     * 
     * @param id 活动信息主键
     * @return 结果
     */
    @Override
    public int deleteActivityById(Long id) {
        //判断当前用户是否有权限修改活动
        SysUser sysUser = sysUserMapper.selectUserById(UserThreadLocal.getUserId());
        if (sysUser.getStatus().equals("0")) {
            //获取用户角色
            List<SysRole> roles = sysUser.getRoles();
            for (SysRole role : roles) {
                //判断角色状态是否正常，是否是普通用户
                if(role.getStatus().equals("0") && role.getRoleKey().equals("admin")){
                    //管理员可以删除所有活动
                    return activityMapper.deleteActivityById(id);
                } else if (role.getStatus().equals("0") && role.getRoleKey().equals("activityPublisher")) {
                    //组织者只能删除自己的活动
                    activityMapper.deleteActivityById(id);
                }
            }
        }
        return 0;
    }

    @Override
    public List<Activity> getList() {
        return activityMapper.selectActivityList(null);
    }
}
